from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os

from html import CheckBox, DropDown, MultiSelect, RadioButton #importing the html wrappers.
import validate #import validation
import tables
import main
import datetime
import staticInits 
import cgi #for escaping html chars in forms
import re


class Setup(webapp.RequestHandler):
    """
    This class deals with the admin add classes view.
    """

    
    def __init__(self):
        webapp.RequestHandler.__init__(self) #parent constructor call

        self.currentState = tables.AppState.get_by_key_name('currentState')
        self.currentSemester = self.currentState.semester
        self.currentTimeName = self.currentState.time.name   
            
        self.timeRadios = ['Admin Setup', 'Ta Apply', 'Instructor Apply', 'Admin Match']   
        self.timeRadios = [RadioButton(name="time", value=timeName, string=timeName, checked=(timeName==self.currentTimeName)) for timeName in self.timeRadios]

 
        
        
    def get(self):
        """
        Calls renderTemplate() for this class.
        """
        self.renderTemplate()

    def post(self):
        """
        Calls renderTemplate() for this class.
        """

        clicked = self.request.get('submit', default_value="default")

        #handles the case semester is incremented or decremented
        if clicked =='next semester':
            orderedSeasonNames = ['spring', 'summer', 'fall']
            currentSeasonName = str(self.currentSemester.season.name)
            currentYear = int(self.currentSemester.year)
            
            for index in xrange(len(orderedSeasonNames)):
                if orderedSeasonNames[index] == currentSeasonName:
                    currentYear = (currentYear - 1) if (currentSeasonName == 'spring' and clicked == '- -') \
                        else ((currentYear + 1) if (currentSeasonName == 'fall' and clicked == 'next semester')   \
                        else currentYear)
                    currentSeasonName = orderedSeasonNames[index-1] if clicked == '- -' else orderedSeasonNames[(index+1)%3]
                    break
            newSemester = tables.Semester(key_name = (currentSeasonName+str(currentYear)), season = tables.Season.get_by_key_name(currentSeasonName), year = currentYear)
            newSemester.put()
            self.currentState.semester = self.currentSemester = newSemester
            assert self.currentSemester == self.currentState.semester == newSemester
            self.currentState.put() 

        # if "Set time" button is clicked we need to change state
        elif clicked == 'Set Time':
            time = self.request.get('time', default_value="default")
            self.currentState.time = tables.Time.get_by_key_name(time)
            self.currentTimeName = self.currentState.time.name
            self.currentState.put()
            self.timeRadios = ['Admin Setup', 'Ta Apply', 'Instructor Apply', 'Admin Match']
            self.timeRadios = [RadioButton(name="time", value=timeName, string=timeName, checked=(timeName==self.currentTimeName)) for timeName in self.timeRadios]       
            



  
                       
        self.__init__()
        self.renderTemplate()
    
    def renderTemplate(self, addValid = "") :
        """
        Renders the Template setup.html for this class.
        """

        #setting up template dictionary
        templateValues = {
            'timeRadios': self.timeRadios,
            'currentSemester': self.currentSemester,
            }


        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'setup.html')
        self.response.out.write(template.render(path, templateValues))



application = webapp.WSGIApplication([('/admin', Setup)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()



